//
//  SearchWorker.m
//  pkphotomap
//
//  Created by Ed Mancebo on 3/23/11.
//  Copyright 2011 Personal. All rights reserved.
//

#import "SearchWorker.h"
#import "RequestIdGenerator.h"
#import "FlickrAPI.h"
#import "PKImage.h"
#import "MapViewController.h"
#import "SearchResult.h"

#include <libkern/OSAtomic.h>

@implementation SearchWorker

- (void) search:(SearchRequest*)request curImages:(NSDictionary*)curImageIds {
	
	static volatile int executed = 0;
	static volatile int cancelled = 0;
	
	// cancel this unit of work if rid is stale
	int curRid = [RequestIdGenerator getCurrentId];
	if (curRid > request.rid) {
		OSAtomicIncrement32(&cancelled);
		NSLog(@"cancelled = %d", cancelled);
		return;
	}
	
	// add delay to get more cancels of unecessary operations
	[NSThread sleepForTimeInterval:2.0];
	curRid = [RequestIdGenerator getCurrentId];
	if (curRid > request.rid) {
		OSAtomicIncrement32(&cancelled);
		NSLog(@"cancelled = %d", cancelled);
		return;
	}
	
	OSAtomicIncrement32(&executed);
	NSLog(@"executed = %d", executed);
	
	// get relevant image IDs for this geographical area by calling
	// flickr search api
	NSMutableArray *imageList = [FlickrAPI searchRegionMin:request.minCoord max:request.maxCoord];
	
	for (PKImage *image in imageList) {
		// break out if another request comes in
		curRid = [RequestIdGenerator getCurrentId];
		if (curRid > request.rid)
			break;
		
		// only fetch data for imageIds that are not already in the model
		if ([curImageIds objectForKey:image.imageId] == nil) {
			// eager load coordinates and thumbnail
			[image loadInfo];
			[image getThumbImage];
			
			NSMutableArray *pkImages = [[NSMutableArray alloc] init];
			[pkImages addObject:image];
			SearchResult *result = [[SearchResult alloc] initWithRid:request.rid images:pkImages];
			[pkImages release];	
			
			// check rid again and update model on main thread
			[self performSelectorOnMainThread:@selector(updateModel:) withObject:result waitUntilDone:NO];
			[result release];
		}
	}
	
	//[request release]; // allocated by search engine
}

- (void) updateModel:(SearchResult*)result {
	int curRid = [RequestIdGenerator getCurrentId];
	if (curRid > result.rid)
		return;
	
	MapViewController *mapViewController = [MapViewController getInstance];
	[mapViewController addVisibleImages:result.pkImages];
}

@end
